package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private ShoppingCartMapper shoppinCartMapper;
    @Autowired
    private SetmealMapper  setmealMapper;
    @Override
    public void addCart(ShoppingCartDTO dto) {
        //创建ShoppingCart对象
        ShoppingCart shoppingCart = new ShoppingCart();
        //拷贝前端传过来的属性值
        BeanUtils.copyProperties(dto,shoppingCart);
        //1.判断商品是否已在购物车中--条件：dishId+dishFlavor+userId
        //只查当前用户自己的购物车
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart cart=shoppingCartMapper.selectBy(shoppingCart);
        if(cart==null)//代表购物车没有该商品数据
        {
            //2.补充缺失的属性值
            //判断当前是 新增套餐还是新增菜品
            if(dto.getDishId()!=null) //代表是新增菜品
            {
                //根据菜品Id查询菜品表，获取菜品相关信息
                Dish dish = dishMapper.getById(dto.getDishId());
                shoppingCart.setName(dish.getName());
                shoppingCart.setName(dish.getPrice());
                shoppingCart.setImage(dish.getImage());
            }
            else
            {
                //代表是套餐
                Setmeal setmeal = setmealMapper.getById(dto.getSetmealId());
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setName(setmeal.getPrice());
                shoppingCart.setImage(setmeal.getImage());
            }
            shoppingCart.setNumber(1);   //数量--》到底是1还是加1？判断该商品是否已经存在购物车
            shoppingCart,setCrateTime(LocalDateTime.now());
            //将商品存入到shopping_cart表中
        }
        else //代表购物车有该商品数据
        {
            //4.将原来的购物车商品数量+1，调用mapper更新方法
            cart.setNumber(cart.getNumber()+1);
            shoppinCartMapper.update(cart);
        }

    }

    @Override
    public void clean() {
        //注意：只能清空自己名下的购物车的数据
        shoppinCartMapper.delete(BaseContext.getCurrentId());
    }
}
